<?php
$path=drupal_get_path('module', 'announcements') ;
drupal_add_js(drupal_get_path('module', 'announcements') . '/js/announcements.js');
drupal_add_css($path . '/css/announcements.css');

global $date_obj;

class ann_date_range{
	public $startdate,$enddate,$num_loop=0;
	public function __construct(){

		$cur_month = date('m');
		if($cur_month >= '01' && $cur_month <= '03'){
			$cur_year = date('Y');
			$pre_year =  date("Y",strtotime("-1 year"));
			$this->startdate = $pre_year.'-04-01';
			$this->enddate = $cur_year.'-03-31';

			$num = $this->node_available();
			if(empty($num)){
			$this->startdate = $this->get_prev_year_with_date($this->startdate);
			$this->enddate = $this->get_prev_year_with_date($this->enddate);
			$this->node_available();
		}

		}
		if($cur_month >= '04' && $cur_month <= '12'){
			 $cur_year = date('Y');
			 $nxt_year =  date("Y",strtotime("+1 year"));
			 $this->startdate = $cur_year.'-04-01';
			 $this->enddate = $nxt_year.'-03-31';

			$num = $this->node_available();
			if(empty($num)){
			$this->startdate = $this->get_prev_year_with_date($this->startdate);
			$this->enddate = $this->get_prev_year_with_date($this->enddate);
			$this->node_available();
		}
		}

	}


	public function node_available(){
		global $language;
		db_set_active('cmsdb');
		$query = db_query("select COUNT(DISTINCT(n.nid)) AS num_of_node from {node} as n,{content_type_announcements} as c  where n.status=1 and n.vid = c.vid and n.nid = c.nid and (n.language ='".$language->language."' OR n.language ='')  AND date(field_annstart_value) BETWEEN '$this->startdate' AND '$this->enddate'");
		//$num = db_fetch_object($query);

		db_set_active('default');
		foreach($query as $num){
			return $num->num_of_node;
		}
	}
	public function get_prev_year_with_date($date){
		$ts = strtotime("last year", strtotime($date));
		$newdate = date('Y-m-d', $ts);
		return $newdate;
	}
}

$date_obj = new ann_date_range();

/**
 * Function for announce_view_data()
 * @return string
 */
function announce_view_data(){

	 $nid = arg(2);
	 $output = '';
	 $output1 = '';

	global $base_url;
	global $language,$date_obj;
	if($language->language=='ta')
	$lang = 'ta';
	else
	$lang = '';

	$strData = "";

	$op1 = get_announcement_header('');

	my_db_change(1);
	$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
	$nodedata = node_load($nid, $vid);
	my_db_change(0);

	$output .= "<div id='result_go' class='result_inner'>";
	if($nodedata){

	//print "<pre>";print_r($nodedata);print "</pre>";

		$strData .='<div class="back_btn"><a href="javascript:history.go(-1)"><strong>'.t("Back").'</strong></a></div>
			<div class="clr"></div>';
		db_set_active('cmsdb');
		$dept_mst_query = db_query("select d.* from depart_mst as d where d.dep_id=".$nodedata->field_anndept['und']['0']['value']);
		//$dept_mst_data = db_fetch_object($dept_mst_query);
		db_set_active('default');
		foreach($dept_mst_query as $dept){$dept_name = $dept->dept_name;}
		$strData .= '
		<span class = "left_column">'.t("Concerned Department").' </span>
		<span class = "middle_column"> : </span>
		<span class = "right_column">'.t($dept_name).'</span>
		<div class="clr"></div>
		';
		db_set_active('cmsdb');
		$dept_org_query = db_query("select n.* from node as n where n.nid=".$nodedata->field_ann_org['und']['0']['value']);
		//$dept_org_data = db_fetch_object($dept_org_query);
		db_set_active('default');
		foreach($dept_org_query as $org){$org_name = $org->title;}
		$strData .= '
		<span class = "left_column">'.t("Organisation Name").'</span>
		<span class = "middle_column"> : </span>
		<span class = "right_column">'.t($org_name).'</span>
		<div class="clr"></div>
		';
		$strData .= '
		<span class = "left_column">'.t("Announcement Details").'</span>
		<div class="clr"></div>
		<span class = "left_column"><span class="whitespace"></span>'.t("Title").'</span>
		<span class = "middle_column"> : </span>
		<span class = "right_column">'.$nodedata->title.'</span>
		<div class="clr"></div>
		<span class = "left_column"><span class="whitespace"></span>'.t("Type").'</span>
		<span class = "middle_column"> : </span>
		<span class = "right_column">'.t($nodedata->field_ann_type['und']['0']['value']).'</span>
		<div class="clr"></div>
		';
		 if ($nodedata->field_ann_type['und']['0']['value']=='Others'){

			$strData .='<span class = "left_column"><span class="whitespace"></span>'.t("Other Detail").'</span>
			<span class = "middle_column"> : </span>
			<span class = "right_column">'.$nodedata->field_anntothers['und'][0]['value'].'</span>
			<div class="clr"></div>
			';
		}

		$strData .='<span class = "left_column"><span class="whitespace"></span>'.t("Date of Announcement").'</span>
		<span class = "middle_column"> : </span>
		<span class = "right_column">'.date("d-m-Y", strtotime($nodedata->field_annstart['und'][0]['value'])).'</span>
		<div class="clr"></div>
		<span class = "left_column">'.t("Description").'</span>
		<span class = "middle_column"> : </span>
		<span class = "right_column">'.$nodedata->field_anndesc['und']['0']['value'].'</span>
		<div class="clr"></div>
		';


		if(($nodedata->field_annavail['und']['0']['value']=='Downloadable') || ($nodedata->field_annavail['und']['0']['value']=='OnlineAvailable')){
			$strData .='<span class = "left_column">'.t("Announcement Available").'</span>
			<span class = "middle_column"> : </span>
			<span class = "right_column">'.t($nodedata->field_annavail['und']['0']['value']).'</span>
			<div class="clr"></div>
			';
		}
		if($nodedata->field_annavail['und']['0']['value']=='OnlineAvailable'){
			$strData .='<span class = "left_column"><span class="whitespace"></span>'.t("URL").'</span>
			<span class = "middle_column"> : </span>
			<span class = "right_column">';
			$filepath=$nodedata->field_annurl['und'][0]['value'];
			$strData .='<a href="javascript:void(0);" onClick="return tnportal_ext_window(\''.$filepath.'\');">'.$filepath.'</a>';
			$strData .='</span>
			<div class="clr"></div>
			';
		}
		if($nodedata->field_annavail['und']['0']['value']=='Downloadable'){
			$strData .='<span class = "left_column"><span class="whitespace"></span>'.t("File").'</span>
			<span class = "middle_column"> : </span>
			<span class = "right_column">';
			$filename = '';
			if($nodedata->field_anndown){
    		    $filename = $nodedata->field_anndown['und']['0']['filename'];
    		    $filesize = $nodedata->field_anndown['und'][0]['filesize'];
    			$icon = get_pdf_icon($filesize)	;
    						 	//$filepath = $baseurl.$contentlist->filepath;
    							$wrapper = file_stream_wrapper_get_instance_by_uri($nodedata->field_anndown['und']['0']['uri']);

    							if($wrapper == true){
    								$filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($nodedata->field_anndown['und']['0']['uri']);

    							}
			}
			//$ext_links = $fpath;
			//$icon = get_pdf_icon($ext_links);
			if($filename){
			$strData .="<a target='_blank' href='http://cms.tn.gov.in/tncms_latest/" .$filepath. "'>".$filename.$icon.'</a>';
			}else{
			$strData .= '<a>-</a>';
			}
			$strData .='</span>
			<div class="clr"></div>
			';
		}


	}
	$output1 .='</div>';
	if($nodedata){
		$output .= $strData;
	}else {
		$output .=' <div class="no_record">'.t('No Results Found').' </div>';
	}
	return $op1.$output.$output1;

}

function fullannouncementsdata(){


		global $language,$date_obj;
	$op = '';
	$output = '';
	db_set_active('cmsdb');
	$op1 = get_announcement_header('');
	$css = '/css/circulars.css';
	$module_path = drupal_get_path('module', 'announcements');
	if($language->language=='ta'){
	  $lang = 'ta';
	}
	else{
	  $lang = '';
	}

	/*
	$qry = db_select('depart_mst','d');
		$qry->fields('d',array('dep_id','dept_name'))->distinct();
		$qry->addJoin('INNER','field_data_field_anndept','ad', 'd.dep_id = CAST(ad.field_anndept_value AS INT)');
		$qry->addJoin('INNER','node','n','n.nid = ad.entity_id' );
	    $qry->addJoin('INNER','field_data_field_annstart','anst','n.nid = anst.entity_id');
		$qry->condition('n.status', 1);
		//$qry->condition('anst.field_annstart_value',array($date_obj->startdate,$date_obj->enddate),'BETWEEN');
		$qry->fields('n',array('nid','title'));
		$qry->condition('n.language',$lang ,'=');
		$qry->orderby('d.dep_id','ASC');

	$result = $qry->execute();
	*/

	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
		->entityCondition('bundle', 'announcements')
		->propertyCondition('status',1)
		->fieldOrderBy('field_anndept', 'value', 'ASC')
		->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN');

	$result = $query->execute();

	if (isset($result['node'])) {
		$news_items_nids = array_keys($result['node']);
	}


	db_set_active('default');

	foreach($news_items_nids as $nid){
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$res = node_load($nid, $vid);
		my_db_change(0);

			if($language->language == 'ta'){
			 	$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->title), 'ta/announcements/announce_view/' . $res->nid) . "</p> </div>" ;
			}else{
				$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->title), 'announcements/announce_view/' . $res->nid) . "</p> </div>" ;
			}

	}
	$output .= $op1;
	$output .='<div class="result_inner">';
	$output .= $op;
	$output .= "</div><div class='clr'></div></div>";


	return $output;

}

function announcements_department_list(){

	global $language,$date_obj;
    $op = '';
    $output = '';
	//print_r($date_obj);

	db_set_active('cmsdb');

	$op1 = get_announcement_header('');
	//$css = '/css/circulars.css';
	//$module_path = drupal_get_path('module', 'announcements');
	if($language->language=='ta')
	$lang = 'ta';
	else
	$lang = '';


	$qry = db_select('depart_mst','d');
		$qry->fields('d',array('dep_id','dept_name'))->distinct();
		$qry->addJoin('INNER','field_data_field_anndept','ad', 'd.dep_id = CAST(ad.field_anndept_value AS INT)');
		$qry->addJoin('INNER','node','n','n.nid = ad.entity_id' );
		$qry->addJoin('INNER','field_data_field_annstart','anst','n.nid = anst.entity_id');
		$qry->condition('n.status', 1);
		$qry->condition('anst.field_annstart_value',array($date_obj->startdate,$date_obj->enddate),'BETWEEN');
		//$qry->condition('n.language', $lang,'=');
		$qry->orderby('d.dep_id','ASC');


	$result = $qry->execute();
	db_set_active('default');

	foreach($result as $res){

			if($language->language == 'ta'){
			 	$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->dept_name), 'ta/announcements/dept_list/' . $res->dep_id) . "</p> </div>" ;
			}else{
				$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->dept_name), 'announcements/dept_list/' . $res->dep_id) . "</p> </div>" ;
			}

	}
	$output .= $op1;
	$output .= "<div id='result_go' class='result_inner'>";
	$output .= $op;
	$output .= "</div><div class='clr'></div>";


	return $output;


}

/**
 * Function for announcements_dept_data()
 * @return string
 */
function announcements_dept_data(){

	global $language;
	$dep_val = arg(2);
    $op = '';
    $output = '';

	db_set_active('cmsdb');

	$op1 = get_announcement_header('');

	//drupal_add_css(drupal_get_path('module', 'go_view') . 'css/go_view.css');
	//$op = "<div id='viewmod_govtinterest' class='view-header'>" . get_announcement_header( 'dept' ) ."</div>";

	//$op .= "<div class='go_view'><div class='back_btn'><span>" .l(t('Back'),'circulars/dept'). "</span></div>";


	$depname = db_query('SELECT dept_name FROM {depart_mst} WHERE dep_id = :dep_id', array(':dep_id' => $dep_val))->fetchField();



	$op1 .= "<div id='result_go' class='result_inner'>" . "<div class='res_dept'><span >" . t($depname) . "</span>
			<span class='backbut'>" .l(t('Back'),'announcements/dept_list'). "</span></div>";


	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
		->entityCondition('bundle', 'announcements')
		->fieldCondition('field_anndept', 'value', $dep_val, '=')
		->propertyOrderBy('title','ASC')
		->propertyCondition('status',1)
		->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN')
		->pager(15,0);

	$result = $query->execute();

	if (isset($result['node'])) {
		$news_items_nids = array_keys($result['node']);
	}
	db_set_active('default');
	foreach($news_items_nids as $nid){
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$res = node_load($nid, $vid);
		my_db_change(0);

		if($language->language == 'ta'){
		 	$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->title), 'ta/announcements/announce_view/' . $res->nid) . "</p> </div>" ;
		}else{
			$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->title), 'announcements/announce_view/' . $res->nid) . "</p> </div>" ;
		}
	}
	$output .= $op1;
	if(count($news_items_nids)){
	$output .= $op;
	}else{
	$output .=' <div class="no_record">'.t('No Results Found').' </div>';
	}
	$output .= "</div><div class='clr'></div>";

	return $output;
}

/**
 * Function announcements_atoz()
 * @return string
 */
function announcements_atoz(){

	global $language,$date_obj;
    $sel = strtolower(arg(2));
	$st_date = $date_obj->startdate;
	$op = '';
	$output = '';
	//print $end_date = $date_obj->enddate;

	db_set_active('cmsdb');

	$module_path = drupal_get_path('module', 'announcements');

	$op1 = get_announcement_header( 'atoz' );
	$op1 .= "<div class='view-header'>" . Doc_AtoZ_letters( $sel ) . "</div><div class='result_inner'>";
	$op .= "<div class='go_view'><div class='back_btn'><span>" .l(t('Back'),'announcements/atoz'). "</span></div>";

	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
		->entityCondition('bundle', 'announcements')
		->fieldCondition('field_annstart', 'value', $st_date, '>')
		->propertyOrderBy('title','ASC')
		->propertyCondition('status',1)
		->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN');

	$result = $query->execute();

	if (isset($result['node'])) {
		$news_items_nids = array_keys($result['node']);
	}

	db_set_active('default');

	foreach($news_items_nids as $nid){
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$res = node_load($nid, $vid);
		my_db_change(0);

		// print "<pre>";print_r($res); print "</pre>";
		$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->title), 'announcements/announce_view/' . $res->nid) . "</p> </div>" ;
	}
	$output .= $op1;
	if(count($news_items_nids)){
		$output .= $op;
	}else{
		$output .=' <div class="no_record">'.t('No Results Found').' </div>';
	}
	$output .= "<div class='clr'></div></div>";

	return $output;

}

/**
 * Function announcements_atoz_letter()
 * @return string
 */
function announcements_atoz_letter(){

	global $language,$date_obj;

	$letter_val = arg(2);
	$st_date = $date_obj->startdate;
    $op = '';
    $output = '';

	db_set_active('cmsdb');

	$module_path = drupal_get_path('module', 'announcements');

		$op1 = get_announcement_header( 'atoz' );
		$op1 .= "<div class='view-header'>" . Doc_AtoZ_letters( $letter_val ) . "</div><div class='result_inner'>";
		$op .= "<div class='go_view'><div class='back_btn'><span>" .l(t('Back'),'announcements/atoz'). "</span></div>";

	//$qry = db_select('node','n');

	if($letter_val !='All') {

		$query = new EntityFieldQuery();
		$query->entityCondition('entity_type', 'node')
			->entityCondition('bundle', 'announcements')
			->fieldCondition('field_annstart', 'value', $st_date, '>')
			->propertyCondition('title',$letter_val.'%','LIKE')
			->propertyOrderBy('title','ASC')
			->propertyCondition('status',1)
			->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN');
	}
	else{

		$query = new EntityFieldQuery();
		$query->entityCondition('entity_type', 'node')
			->entityCondition('bundle', 'announcements')
			->fieldCondition('field_annstart', 'value', $st_date, '>')
			->propertyOrderBy('title','ASC')
			->propertyCondition('status',1)
			->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN');
	}
	//$ann_result = $qry->extend('PagerDefault')->limit(20)->execute();
	$result = $query->execute();

	if (isset($result['node'])) {
		$news_items_nids = array_keys($result['node']);
	}

	db_set_active('default');

	foreach($news_items_nids as $nid){
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$res = node_load($nid, $vid);
		my_db_change(0);

		$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->title), 'announcements/announce_view/' . $res->nid) . "</p> </div>" ;

	}
		$output .= $op1;
		if(count($news_items_nids)){
			$output .= $op;
		}else{
			$output .=' <div class="no_record">'.t('No Results Found').' </div>';
		}
		$output .= "<div class='clr'></div></div>";


		return $output;


}

function Doc_AtoZ_letters($sel ){
	global $base_url;
	$linkOp = '';
	$listArr = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "All" );
	/*foreach ($listArr as $key => $val )	{
		if ($sel == $val || strtolower($sel ) == strtolower($val ) ){
			$selected = 'view_head_sel';
		}
		else{
			$selected = 'view_head_nonsel';
		}*/
	for($i =65; $i < 91; $i++){
		$class = "";
		if(chr($i) == $sel){
			$class = " view_head_sel";
		}
		else
		{
			$class = " view_head_nonsel";
		}
		//$linkOp .= l($val,'announcements/atoz/'.$val,array('attributes'=>array('class'=>$selected)))."&nbsp;&nbsp;";
		$linkOp .='<a class="'.$class.'" href="'.$base_url.'/announcements/atoz/'.chr($i).'">'.chr($i).'</a>&nbsp;&nbsp;';
	}
	$class = "";
	if($sel == 'All' || $sel == ''){
		$class = " view_head_sel";
	}
	else
		{
			$class = " view_head_nonsel";
		}
	$linkOp .= '<a class = "myclass' . $class . '"  href="'.$base_url.'/announcements/atoz/All" title = "All" id = "All"> All </a>';
	
	$StrOp = "<div class='result_inner_atoz'>";
	$StrEnd = "</div>";
	$Grey = "<div class='grey_bord_line'></div>";
	return $StrOp . $linkOp . $Grey . $StrEnd;
}

function announcements_category(){

		//unset_search_session('anno_search');
		global $base_url;
		
		$docheader = get_announcement_header('cate' );

		/*if (!empty($_SESSION['anno_dept'])) {
			$depts = $_SESSION['anno_dept'];
			$joinClause = " and c.field_anndept_value='".$depts."'";
		} */
		$form = drupal_get_form("announcements_category_list_form");
		$op1 = "<div>" . drupal_render($form). "</div>";
		$op = "<div id = 'announce_content'></div>";
		$StrOp = "<div class='result_inner'>";
		$StrEnd = "<div class='clr'></div></div>";
		$output = $docheader . $StrOp . $op1 . $op . $StrEnd;
		return $output;


}

/*function announcements_district(){
	
		global $base_url;
		
		$docheader = get_announcement_header('district' );

		$op .= "<div>" . drupal_render(drupal_get_form("announcements_district_list_form") ). "</div>";
		$op .= "<div id = 'announce_content'></div>";
		$StrOp = "<div class='result_inner'>";
		$StrEnd = "<div class='clr'></div></div>";	
		$output = $docheader . $StrOp . $op . $StrEnd;
		return $output;
}*/
function announcements_district(){
   
        global $base_url;
		 global $language,$date_obj;
         
        $docheader = get_announcement_header('district' );
     
        $op1 .= "<div>" . drupal_render(drupal_get_form("announcements_district_list_form") ). "</div>";    
       
   
    $st_date = $date_obj->startdate;

    $module_path = drupal_get_path('module', 'announcements');
   
     $dist_id ='0' ;    
    db_set_active('cmsdb');
   
         
    $query = db_select('node', 'n');
        $query->fields('n', array('nid','title'))->distinct();
        $query->condition('n.type', 'announcements');
        $query->condition('n.status', '1');
        $query->condition('n.language', $language->language,'=');
       
        $query->addJoin('INNER','field_data_field_anndist', 'andis', 'n.nid = andis.entity_id');
        $query->addJoin('INNER','field_data_field_annstart','anst','n.nid = anst.entity_id');
        $query->join('file_usage', 'fu','n.nid = fu.id');
        $query->join('file_managed', 'fm','fm.fid = fu.fid' );
        $query->addField('fm','uri');
        $query->addField('fm','filesize');
        $query->condition('anst.field_annstart_value',$st_date,'>');
        $query->condition('andis.field_anndist_value', $dist_id,'=');
         
        //print $query;  die;
        $ann_dist = $query->extend('PagerDefault')->limit(20)->execute();

        $row_count = $ann_dist->rowCount();

    db_set_active('default');
   
    if($row_count==''){
        $op = "<div class ='go_box'><strong>" .'No record Found'."</strong></div>";
    }
    foreach($ann_dist as $res) {
        $filepath = $res->uri;
        $fpath_val = SUBSTR($filepath,9,5);
        $filesize = $res->filesize;
        $title = $res->title;   
       
        if(empty($filepath)){       
                            $wrapper = file_stream_wrapper_get_instance_by_uri($res->uri);
                              
                            if($wrapper == true){
                                $filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($res->uri);
                            }
                            $icon = '';
                    }else{
                              $icon = get_pdf_icon($filesize)    ;
                             //$filepath = $baseurl.$contentlist->filepath;   
                            $wrapper = file_stream_wrapper_get_instance_by_uri($res->uri);
                              
                            if($wrapper == true){
                                $filepath = $wrapper->getDirectoryPath() . "/" . file_uri_target($res->uri);
                               
                            }//$department= $contentlist -> dept_name;   
                         
                    }
                   
                    if($filesize != 0){                       
                            $kb = ceil($res->filesize/1024);
                        $kbyte= $kb.KB;
                        if($kb >1024) {
                          $kb = ceil($kb/1024);
                          $kbyte= $kb.MB;
                        }
                    }
       
        if($language->language=='ta'){
        $lang= '/ta';
    }else{
     $lang='';
    }
                if($fpath_val != 'press'){
                    if($res->title != $tit){
                    $tit = $res->title;
                     $op .= "<div class='go_view_dept_list'> <p><a href='$base_url$lang/announcements/announce_view/$res->nid')>".t($res->title). "</a></p> </div>" ;
                    }
                }
        }
        $opStr .= "<div id = 'announce_content'>";
        $opEnd .="</div>";
        $StrOp = "<div class='result_inner'>";
        $StrEnd = "<div class='clr'></div></div>";   
        $output .= $docheader . $StrOp . $op1.$opStr. $op .$opEnd. $StrEnd;
        return $output;
    echo $output;

}

function get_category_result() {
	global $base_url;
	global $language,$date_obj;
	//print_r($language);
	$st_date = $date_obj->startdate;

	$module_path = drupal_get_path('module', 'announcements');

	//$op = get_announcement_header( 'atoz' );

	$category = ($_GET['category']=='')? NULL : $_GET['category'] ;
	//print "Muthukkumar";

	//$module_path = drupal_get_path('module', 'announcements');
	//drupal_add_js(drupal_get_path('module', 'announcements') . 'js/announcements.js');
		//$op = get_announcement_header( 'atoz' );
		//$op .= "<div class='result_inner'><div class='view-header'>" . Doc_AtoZ_letters( $sel ) . "</div>";
		//$op .= "<div class='go_view'><div class='back_btn'><span>" .l(t('Back'),'announcements/atoz'). "</span></div>";


	db_set_active('cmsdb');
	/*
	$qry = db_select('node','n');
			$qry->fields('n',array('nid','title'))->distinct();
			//$qry->fields('d',array('dep_id','dept_name'))->distinct();
            //$qry->addField('n','title');
			$qry->addJoin('INNER','field_data_field_ann_type','andow','n.nid = andow.entity_id');
			$qry->addJoin('INNER','field_data_field_annstart','anst','n.nid = anst.entity_id');
			$qry->addJoin('INNER','file_usage','fu','fu.id = n.nid');
			$qry->addJoin('INNER','file_managed','fm','fm.fid = fu.fid');
			$qry->addField('fm','uri');
			$qry->addField('fm','filesize');
			$qry->addField('andow','field_ann_type_value');
            $qry->condition('n.status', '1');
			$qry->condition('n.language', array($GLOBALS['language']->language),'=');
			//$qry->condition('n.language', 'en','=');
			$qry->condition('anst.field_annstart_value',$st_date,'>');

			$qry->condition('andow.field_ann_type_value',$category,'=');

	//print $qry;
	$ann_result = $qry->extend('PagerDefault')->limit(20)->execute();
	*/

	$query = new EntityFieldQuery();
	$query->entityCondition('entity_type', 'node')
		->entityCondition('bundle', 'announcements')
		->fieldCondition('field_annstart', 'value', $st_date, '>')
		->fieldCondition('field_ann_type', 'value', $category, '=')
		->propertyOrderBy('title','ASC')
		->propertyCondition('status', 1)
		->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN');

	$result = $query->execute();

	if (isset($result['node'])) {
		$news_items_nids = array_keys($result['node']);
	}

	db_set_active('default');
	//$i=0;
	//print "<pre>";print_r($ann_result); print "</pre>"; exit;
	foreach($news_items_nids as $nid){
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$res = node_load($nid, $vid);
		my_db_change(0);

		$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->title), 'announcements/announce_view/' . $res->nid) . "</p> </div>" ;
	}
		$output_val .= $op;
		$output_val .= "<div class='clr'></div></div>";
		if(count($news_items_nids)){
			$output .= $op;
		}else {
			$output .=' <div class="no_record">'.t('No Results Found').' </div>';
		}

		echo $output;

	/*if (empty($op) && $category != NULL) {
		$op = RecordnotFound_doc();
	}*/

	//echo $op;
}

function get_district_result() {


	print $language->language;
	//$op = '';
	//$concat_qry = '';
	/*$dbq="select dt_name from district_mst where dt_cd=$dist_id limit 1 ";

	db_set_active('cmsdb');
	$dbq = db_query($dbq);
	db_set_active('default');
	foreach($dbq as $val){

		//print_r($val);
		$distname=$val-> dt_name;
	}*/
	/*if ($dist_id == 0) {
		$concat_qry = " ";
	}
	else {
	  $concat_qry = "(cd.field_anndist_value = '" . $dist_id . "' ) AND ";
	}*/

	global $base_url;
	global $language,$date_obj;

	$st_date = $date_obj->startdate;

	$module_path = drupal_get_path('module', 'announcements');

	//$dist_id == ; exit;

	 $dist_id = empty($_GET['dist'])? '0' : $_GET['dist'] ;
	//$op = get_announcement_header( 'atoz' );

	db_set_active('cmsdb');

	/*
	$query = db_select('node', 'n');
		$query->fields('n', array('nid','title'))->distinct();
		$query->condition('n.type', 'announcements');
		$query->condition('n.status', '1');
		$query->condition('n.language', $language->language,'=');

		$query->addJoin('INNER','field_data_field_anndist', 'andis', 'n.nid = andis.entity_id');
		$query->addJoin('INNER','field_data_field_annstart','anst','n.nid = anst.entity_id');
		$query->join('file_usage', 'fu','n.nid = fu.id');
		$query->join('file_managed', 'fm','fm.fid = fu.fid' );
		$query->addField('fm','uri');
		$query->addField('fm','filesize');
		$query->condition('anst.field_annstart_value',$st_date,'>');
		$query->condition('andis.field_anndist_value', $dist_id,'=');

		//print $query;  die;
		$ann_dist = $query->extend('PagerDefault')->limit(20)->execute();
		//$ann_dist=$query ->execute();
		//$ann_dist = $query->execute();
		$row_count = $ann_dist->rowCount();
		*/

		$query = new EntityFieldQuery();
		$query->entityCondition('entity_type', 'node')
			->entityCondition('bundle', 'announcements')
			->fieldCondition('field_annstart', 'value', $st_date, '>')
			->fieldCondition('field_anndist', 'value', $dist_id, '=')
			->propertyOrderBy('title','ASC')
			->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN')
			->propertyCondition('status', 1)
			->pager(20,0);

		$result = $query->execute();

		if (isset($result['node'])) {
			$news_items_nids = array_keys($result['node']);
		}

	db_set_active('default');

	if(count($news_items_nids)==''){
		$op = "<div class ='go_box'><strong>" .'No record Found'."</strong></div>";
	}

	//print_r($ann_dist);
	//print "<pre>"; print_r($ann_dist); print "</pre>"; die;
	foreach($news_items_nids as $nid) {
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$res = node_load($nid, $vid);
		my_db_change(0);

		if($language->language=='ta'){
			$lang= '/ta';
		}else{
			$lang='';
		}
					if($fpath_val != 'press'){
					if($res->title != $tit){
					$tit = $res->title;
				 	$op .= "<div class='go_view_dept_list'> <p><a href='$base_url$lang/announcements/announce_view/$res->nid')>".t($res->title). "</a></p> </div>" ;
					}
				}
		}




	/*if (empty($op) ) {
		$op = RecordnotFound_doc();
	}*/
	$output =  $op; //$StrOp . $op . $StrEnd;
	echo $output;

}


function announcement_search(){

 	//drupal_set_title('');
	global $base_url;
	global $language,$date_obj;

	//echo "search";
	//$filedname = "field_ann_type_value";
	$output = get_announcement_header('' );
	$form = drupal_get_form('announcement_search_form');
	$drupal_search_form = drupal_render($form);
	$output .= "<div class='result_inner_search'><div style=' width:100%; height:22px;'>".$drupal_search_form."</div>";
	$output .= "<div style='clear:right'></div>";
	$output .="<div style='width:140px; margin-top:10px; margin-left:0px; overflow:hidden;'>&nbsp;</div>";


	return $output;
}

/**
 * Function announcement_search_result()
 * @return string
 */
function announcement_search_result(){

	global $base_url,$language;
	//print $base_url; exit;
	$op = '';
	$output = '';

	$go_year = arg(3);


		//drupal_add_css(drupal_get_path('module', 'go_view') . '/go_view.css');
		$docheader = "<div id='viewmod_govtinterest' class='view-header'>" . get_announcement_header( 'find' ) ."</div>";
		//$op = get_govt_header( '' );
		$form = drupal_get_form('announcement_search_form');
		$docheader .= drupal_render($form);

	//$op .= "<div class='go_view'><div class='back_btn'><span>" .l(t('Back'),'go_view/dept'). "</span></div>";
		$str = strtoupper(trim(arg(2)));


			  //echo $keyword.''.chkbadcharportal($keyword);
			  /*if(chkbadcharportal($str)== FALSE){

					form_set_error('Keywords', t('Keyword field contains bad characters'));
					 drupal_goto('go_view/searchresult');
			 }*/

		$anno_keyword= trim(arg(2));

		$anno_keyword= strtolower($anno_keyword);
		//$ser_string = array();
		$anno_keyword = preg_replace('/[\p{Z}\s]{2,}/u', ' ', $anno_keyword);
		$anno_keyword=pg_escape_string($anno_keyword);

		$len = drupal_strlen($anno_keyword);
		$keyword1 =$anno_keyword;


		/*	// Do not count UTF-8 continuation bytes.
		 if(!empty($keyword1))
		 {
		$position[0]=strpos($keyword1,'"');

		 if($position[0] != "");{

		  $position[1]=strpos($keyword1,'"',$position[0]+1);

		  }
		  }
		 if(!empty($position[1]))
		 {
			//echo substr($keyword,1)."</br>";
			$k=0;
			for($i=0;$i<=$len;$i++)
			{

			$position[0]=strpos($keyword1,'"');

			if(strlen($keyword1) !=0)
			{
			if($position[0] !=0 && $position[0] !="")
			$str_not_quote[$k++] =substr($keyword1,0,$position[0]);
			if($position[0] ==false)
			$str_not_quote[$k++] =substr($keyword1,0,strlen($keyword1));
			}


			 $position[1]=strpos($keyword1,'"',$position[0]+1);

			 if(empty($position[1]))
			 {
			 break;
			 }
			 $sub_string_len = $position[1] - $position[0]-1;

		 $ser_string[$i] = substr($keyword1,$position[0]+1, $sub_string_len);

			 $part_string= substr($keyword1,$position[1]+1, $len);

			$keyword1 =trim($part_string);
			if(empty($keyword1))
			{
			break;
			}
			}
			}
			$ser_string = array_filter_customize($ser_string);
			//print_r($ser_string);
			if(!empty($ser_string))
			{

				$sql_search_clause = search_keyword('LOWER(n.title)', $ser_string, $str_not_quote);
				$sql_search_clause .= "or ";
				$sql_search_clause .= search_keyword('LOWER(g.field_go_abstract_value)', $ser_string, $str_not_quote);
			}*/

	if(empty($anno_keyword)){ 	//echo "empty";
		//$op = "<div class ='go_box'><strong>" .'Please Enter The Keyword'. "</strong></div>" ;
		$docheader = get_announcement_header( '' );
		$StrOp = "<div class='result_inner' id='result_go'><div class='go_view'>";
		$StrEnd = "<div class='clr'></div></div><div class='clr'></div></div>";
		$form = drupal_get_form('announcement_search_form');
		$output =  $docheader.$StrOp . drupal_render($form).$StrEnd;
		return $output;
	}
	/*if(chkbadchar_search_key($anno_keyword) == 0){
	$op = "<div class ='go_box'><strong>" .'Keyword contain bad character'. "</strong></div>" ;
	//drupal_set_message('keyword contain bad character');
	$docheader = get_announcement_header( '' );
		$StrOp = "<div class='result_inner' id='result_go'><div class='go_view'>";
		$StrEnd = "<div class='clr'></div></div><div class='clr'></div></div>";
		$output =  $docheader.$StrOp . drupal_render(drupal_get_form('announcement_search_form')).$op.$StrEnd;
		return $output;
	}*/
	/*if(chkbadchar_search_key($anno_search) == 0){
	drupal_set_message('Please choose different keyword to search', $type = 'error');
	$form_state['redirect'] = 'announcements/search';
	return;
	}*/
	$anno_val = $anno_keyword;
	db_set_active('cmsdb');

	/*
	$query = db_select('node', 'n');
		$query->fields('n', array('nid','title'));
		//$query->condition('n.type', 'govt_orders');
		$query->condition('n.status', '1');
		//$query->condition('n.language', 'en');

		$query->addJoin('INNER','field_data_field_annkword', 'annk', 'n.nid = annk.entity_id');
		//$query->addJoin('INNER','field_data_field_go_date', 'gd', 'n.nid = gd.entity_id');
		$query->join('file_usage', 'fu','n.nid = fu.id');
		$query->join('file_managed', 'fm','fm.fid = fu.fid' );
		//$query->addField('gd','field_go_date_value');
		//$query->addField('abs','field_go_abstract_value');
		$query->addField('fm','uri');
		$query->addField('fm','filesize');
		$query->distinct();
		$conditions = db_or();
			$conditions->condition('n.title', $anno_val.'%','LIKE');
         	$conditions->condition('annk.field_annkword_value','%'. $anno_val.'%','LIKE');
       $query->condition($conditions);


		//print $query;

		$result = $query->extend('PagerDefault')->limit(20)->execute();
		$row_count = $result->rowCount();
		*/
		$query = new EntityFieldQuery();
		$query->entityCondition('entity_type', 'node')
			->entityCondition('bundle', 'announcements')
			//->fieldCondition('field_annkword', 'value', "%".$anno_val."%", 'LIKE')
			->propertyCondition('title', "%".$anno_val."%","LIKE")
			//->propertyCondition('language', array($GLOBALS['language']->language, ''), 'IN')
			->propertyCondition('status', 1)
			->pager(20,0);

		$result = $query->execute();

		// Get Count of total search records
		$query_count = new EntityFieldQuery();
		$query_count->entityCondition('entity_type', 'node')
			->entityCondition('bundle', 'announcements')
			->propertyCondition('title', "%".$anno_val."%","LIKE")
			->propertyCondition('status', 1) ;
			//->count();

		$count_result = $query_count->execute();
		if (isset($result['node'])){
			$row_count = count($count_result['node']);
		}

		if (isset($result['node'])) {
			$news_items_nids = array_keys($result['node']);
		}

		//print_r($result);
	db_set_active('default');

	if($row_count==''){
		$val = "<div class ='go_box'><strong>" .'No record Found'."</strong></div>";
	}
	else{
		$val = "<div class ='go_box'><strong>" .$row_count .'  record Found' . "</strong></div>";
	}

	foreach($news_items_nids as $nid) {
		my_db_change(1);
		$vid = db_query('SELECT vid FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
		$res = node_load($nid, $vid);
		my_db_change(0);

		$op .= "<div class='go_view_dept_list'> <p>" .l(t($res->title), 'announcements/announce_view/' . $res->nid) . "</p> </div>" ;
	}


		$head = get_announcement_header( '' );
		$form = drupal_get_form('announcement_search_form');
		$head1 = drupal_render($form);
		$StrOp = "<div class='result_inner' id='result_go'><div class='go_view'>";
		$StrEnd = "<div class='clr'></div></div><div class='clr'></div></div>";
		$output .= $head. $StrOp.$head1.$val.$op.$StrEnd;


	return $output. theme('pager');
}

function announcement_search_form(){
	global $base_url;
	$keyword = trim(arg(2));
	$form[ 'lable' ]=array('#prefix'=>'<div class="test"></div>');
	$form[ 'hidden_content' ] = array('#type' => 'hidden', '#default_value' => 'announcements', );
	$form[ 'anno_search' ] = array('#title' => t('Keyword'), '#type' => 'textfield', '#size' => 35, '#default_value' => $keyword ? $keyword : '', '#prefix' => '<div class="keyword_ann">', '#description'=>'<div class="keyword_ann_descr">(Search By Title Eg: Announcements of Cooperation Department)');
	$form[ 'search_subm' ] = array('#title' => 'Submit', '#type' => 'submit', '#value' => t('Search'), '#name' => 'search', '#prefix' => '<div class="sea_go_but">',
	'#suffix' => '</div></div>',);
	return $form;
}

function announcement_search_form_submit($form, &$form_state){

	//print "<pre>"; print_r($form_state); print "</pre>";die;
	//if ($form_state[clicked_button]['#name'] == 'search'){
		  $anno_search = $form_state['values']['anno_search'];


	if ($form_state['clicked_button']['#name'] == 'search') {
			$str = $form_state['values']['anno_search'];
			if(empty($str)) {
			form_set_error('anno_search','Keyword is required');
			//echo 'Please Enter Key Word';
			}

		}

	if(chkbadchar_search_key($anno_search) == 0){
	drupal_set_message('Please choose different keyword to search', $type = 'error');
	$form_state['redirect'] = 'announcements/search';
	return;
	}

	$form_state['redirect'] = 'announcements/searchresult/'.$str;
	return;
}//to get the atoz letters

function chkbadchar_search_key($str){



  $badch = array('/');
	//print_r($badch);

  if (!(is_null($str)) || trim($str)!="") {
    for ($i=0;$i<count($badch);$i++) {
      if (strpos(strtoupper($str),$badch[$i]) !== false) {

        return 0;
      }
    }
  }
  return 1;

} //function chkbadchar()


function get_announcement_header($css){
	drupal_add_js(drupal_get_path('module', 'announcements') . 'php/announcements.js');
	global $base_url;
	global $language;
	if($language->language=='ta')
		$lang = '/ta';
	else
		$lang = '';


	$listvalue=arg(1); // Announcement List value get in the arrgument[1] array
	if($css=='atoz'){ $atoz= "view_head_sel"." selected";}else {$atoz= "view_head_nonsel";}
	if($css=='cate'){ $cat="view_head_sel"." selected"; }else { $cat='view_head_nonsel';}
	if($css=='dept') { $dept="view_head_sel"." selected"; }else{ $dept='view_head_nonsel'; }
	if($css=='district') { $dist="view_head_sel"." selected"; }else {$dist='view_head_nonsel'; }

	$div = "<select id='selectedResult' name='announcement_list' onchange='return GoSub(this.value);' >
	<option value=''>--".t('Select')."--</option>";

	if($language->language != 'ta')
		$div .= "<option value='".$base_url.$lang."/announcements/atoz' " . $atoz .">".t('AtoZ')."</option>";

	$div .= "<option value='".$base_url.$lang."/announcements/category' ". $cat . ">".t('Category')."</option>
	<option value='".$base_url.$lang."/announcements/dept_list' ". $dept . " >".t('Department')."</option>
	<option value='".$base_url.$lang."/announcements/district' "  .$dist . ">".t('Districts')."</option>
	</select>";

 	if ($css=="find") { $find="view_head_sel"; } else { $find= "view_head_nonsel"; }
	$search = "search";

	global $language;
	if($language->language=='ta'){$css='announcements_ta'; } else{ $css='announcements'; }

	$html = "<div class='view-header' id='viewmod_$css'>
		<div class='inner_tab_content'>
		<div class='inner_li'> <span class='view_head_nonsel'>".t('List By')." :".$div."</span></div>
		<div class='inner_li'>" .l(t('Search'),'announcements/search')."</div> .

		<div class='clr'></div></div>
	</div>";
	return $html;

}

function announcements_category_list_form($form_state) {



	global $language ,$date_obj;
	$lang_name = $language->language ;
	drupal_add_js(array('language' => $lang_name ), 'setting');
	$sql = "select distinct(field_ann_type_value) from {field_data_field_ann_type} ";
	//WHERE date(field_annstart_value) BETWEEN '$date_obj->startdate' AND '$date_obj->enddate'";
	db_set_active('cmsdb');
	$result = db_query($sql);
	db_set_active('default');
	//$dept = array();
	$cate_wise_list[''] = t('SELECT CATEGORY');
	/*while($links = db_fetch_object($result)) {
		$cate_wise_list[$links->field_ann_type_value] = t($links->field_ann_type_value);

	}	*/
	foreach($result as $val){


		$cate_wise_list[$val->field_ann_type_value] = t($val->field_ann_type_value);
	}
	$form['category_wise'] = array(
		'#type' => 'select',
		'#id' => 'cate_wise',
		'#title' => t('Category'),
		'#default_value' => variable_get('category_wise', ''),
		'#options' => $cate_wise_list,
		'#attributes' => array('onchange' => 'return get_category_annoucements(this.value)'),

	);
	return $form;
}

function announcements_district_list_form($form_state) {

	global $language ;

	$lang_name = $language->language ;
	drupal_add_js(array('language' => $lang_name ), 'setting');
	//drupal_add_js(drupal_get_path('module', 'announcements') . 'js/announcements.js');
	$sql = "select dt_cd,dt_name from {district_mst} order by dt_cd ASC";
	db_set_active('cmsdb');
	$result = db_query($sql);
	db_set_active('default');
	$dept = array();
	$district_list[0] = 'ALL';

	/*while($links = db_fetch_object($result)) {
		$district_list[$links->dt_cd] = t($links->dt_cd);
	}*/

	foreach($result as $val){

		//print_r($val);
		$district_list[$val->dt_cd] = t($val->dt_name);
	}

	$form['district_wise'] = array(
		'#type' => 'select',
		'#id' => 'district_wise',
		'#title' => t('District'),
		'#default_value' => variable_get('district_wise', 'All'),
		'#options' => $district_list,
		'#attributes' => array('onchange' => 'get_district_announcements(this.value)'),


	);
	//print "<pre>"; print_r($form); print "</pre>";die;
	return $form;
}

?>